package com.poisonh.unifiedauth.ui;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.ImageUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.Photoutils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import io.realm.Realm;


/**
 * 相机界面
 * Created by sky on 15/7/6.
 */
public class CameraActivity extends BaseActivity {

    private Camera mCamera;
    private Camera.Parameters parameters = null;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    private Camera.Size adapterSize = null;
    private Camera.Size previewSize = null;

    private static final String TAG = "Camera";

    private Handler mhandler = new Handler();
    private static Uri IMAGE_FILE_NAME;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //SVProgressHUD.dismiss(CameraActivity.this);等上传到后台之后再停止转圈加载
//                    setResult(SettingCardActivity.CODE_CAMERA_REQUEST, getIntent());
//                    finish();

                    if (hasSdcard()) {
                        File tempFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "head.png");//获取根目录下的文件,
                        String filePath = ImageUtils.scaleSaveBitmap(CameraActivity.this, tempFile.getAbsolutePath());
//                        Photoutils.savePhoto(BitmapFactory.decodeFile(filePath), Environment.getExternalStorageDirectory().getAbsolutePath(), "head");
//                        File file = new File(filePath);
//                        if (file.exists()) {
//                            file.delete();
//                        }
                        //  cropRawPhoto(Uri.fromFile(tempFile));//原来要用的工具类
//                        setImageToHeadView(filePath);

                        UploadPicture(filePath);//请求人脸识别的方法 //取出本地图片

                     //   UploadPicture(tempFile.getAbsolutePath());

                       // UploadPicture(tempFile.getAbsolutePath());

                    } else {
                        Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG).show();
                    }


                    break;
            }
        }
    };

    private DisplayMetrics displayMetrics = null;

    /**
     * 最小预览界面的分辨率
     */
    private static final int MIN_PREVIEW_PIXELS = 480 * 320;

    /**
     * 最大宽高比差
     */
    private static final double MAX_ASPECT_DISTORTION = 0.2;

    //图片存放位置
    public static String name;

    @Override
    protected void loadContentView(Bundle savedInstanceState) {
        IMAGE_FILE_NAME = (Uri) (getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT));
        setContentView(R.layout.activity_camera);
        SurfaceView surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
        //surfaceView.getHolder().setFixedSize(176, 144);  //设置Surface分辨率
        surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮
        surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数

        initTitleView();
        initView();




    }

    @Override
    protected void initView() {

        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setVisibility(View.GONE);
        setTitleTxt("身份认证");


        // 在Capture按钮中加入listener
        Button captureButton = (Button) findViewById(R.id.btn_take_picture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 从摄像头获取图片
                SVProgressHUD.showWithStatus(CameraActivity.this, "处理中...");
                mCamera.takePicture(null, null, new MyPictureCallback());
            }
        });
    }

    private final class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(final byte[] data, final Camera camera) {

            // final  byte[] _data = data;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //  File pictureFile = new File(IMAGE_FILE_NAME.getPath());
//                    FileOutputStream fos =null;
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(_data, 0, _data.length);
//                    Matrix matrix = new Matrix();
//                    matrix.preRotate(90+180);
//                    matrix.postScale(-1, 1);
//                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                    //  Photoutils.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), "head");

                    try {
//                        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                        Matrix matrix = new Matrix();
//                        matrix.preRotate(90 + 180);
//                        matrix.postScale(-1, 1);
//                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//                        Photoutils.scaleSaveBitmap(bitmap,Environment.getExternalStorageDirectory().getAbsolutePath()+ "/head.png");//保存并压缩到本地


//                        bundle = new Bundle();
//                        bundle.putByteArray("bytes", data); //将图片字节数据保存在bundle当中，实现数据交换

                        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        Matrix matrix = new Matrix();
                        matrix.preRotate(90+180);
                        matrix.postScale(-1, 1);
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        Photoutils.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), "head");


                      //  Photoutils.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), "head");
                        // Toast.makeText(getApplicationContext(), R.string.success,Toast.LENGTH_SHORT).show();
                        // saveToSDCard(data); // 保存图片到sd卡中
                        //  camera.startPreview(); // 拍完照后，重新开始预览
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
            }).start();

        }
    }


    private final class SurfaceCallback implements SurfaceHolder.Callback {

        // 拍照状态变化时调用该方法
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            autoFocus();
        }

        // 开始拍照时调用该方法
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            try {
                mCamera = getCameraInstance(); // 打开摄像头
                mCamera.setPreviewDisplay(holder);
                initCamera();
                mCamera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 停止拍照时调用该方法
        @Override
        public void surfaceDestroyed(SurfaceHolder arg0) {
            // TODO Auto-generated method stub
            if (mCamera != null) {
                mCamera.release(); // 释放照相�?
                mCamera = null;
            }
        }

    }

    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    public static void saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/finger/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }


//    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
//    public static int getPreviewDegree(Activity activity) {
//        // 获得手机的方向
//        int rotation = activity.getWindowManager().getDefaultDisplay()
//                .getRotation();
//        int degree = 0;
//        /// 根据手机的方向计算相机预览画面应该选择的角度
//        switch (rotation) {
//            case Surface.ROTATION_0:
//                degree = 90;
//                break;
//            case Surface.ROTATION_90:
//                degree = 0;
//                break;
//            case Surface.ROTATION_180:
//                degree = 270;
//                break;
//            case Surface.ROTATION_270:
//                degree = 180;
//                break;
//        }
//        return degree;
//    }

    /**
     * 安全获取Camera对象实例的方法
     */
    public static Camera getCameraInstance() {

        int useIndex = 0;
        int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                useIndex = i;
                break;
            }
        }
        Camera c = null;
        try {
            c = Camera.open(useIndex); // 试图获取Camera实例
//            c.setDisplayOrientation(270);//设置成竖屏显示
//            Camera.Parameters params = c.getParameters();
//            List<Camera.Size> list = params.getSupportedPreviewSizes();
//            params.setPreviewSize(list.get(0).width,list.get(0).height);
//            c.setParameters(params);
        } catch (Exception e) {
            e.printStackTrace();
            // 摄像头不可用（正被占用或不存在）
        }
        return c; // 不可用则返回null
    }


    private void initCamera() {
        parameters = mCamera.getParameters();
        parameters.setPictureFormat(PixelFormat.JPEG);
        //if (adapterSize == null) {
        setUpPicSize(parameters);
        setUpPreviewSize(parameters);
        //}
        if (adapterSize != null) {
            parameters.setPictureSize(adapterSize.width, adapterSize.height);
        }
        if (previewSize != null) {
            parameters.setPreviewSize(previewSize.width, previewSize.height);
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
        } else {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        setDispaly(parameters, mCamera);
        try {
            mCamera.setParameters(parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
        mCamera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上
    }

    private void setUpPicSize(Camera.Parameters parameters) {

        if (adapterSize != null) {
            return;
        } else {
            adapterSize = findBestPictureResolution();
            return;
        }
    }


    private Camera.Size findBestPictureResolution() {
        Camera.Parameters cameraParameters = mCamera.getParameters();
        List<Camera.Size> supportedPicResolutions = cameraParameters.getSupportedPictureSizes(); // 至少会返回一个值

        StringBuilder picResolutionSb = new StringBuilder();
        for (Camera.Size supportedPicResolution : supportedPicResolutions) {
            picResolutionSb.append(supportedPicResolution.width).append('x')
                    .append(supportedPicResolution.height).append(" ");
        }
        Log.d(TAG, "Supported picture resolutions: " + picResolutionSb);

        Camera.Size defaultPictureResolution = cameraParameters.getPictureSize();
        Log.d(TAG, "default picture resolution " + defaultPictureResolution.width + "x"
                + defaultPictureResolution.height);

        // 排序
        List<Camera.Size> sortedSupportedPicResolutions = new ArrayList<Camera.Size>(
                supportedPicResolutions);
        Collections.sort(sortedSupportedPicResolutions, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size a, Camera.Size b) {
                int aPixels = a.height * a.width;
                int bPixels = b.height * b.width;
                if (bPixels < aPixels) {
                    return -1;
                }
                if (bPixels > aPixels) {
                    return 1;
                }
                return 0;
            }
        });

        // 移除不符合条件的分辨率
        double screenAspectRatio = (double) getScreenWidth()
                / (double) getScreenHeight();
        Iterator<Camera.Size> it = sortedSupportedPicResolutions.iterator();
        while (it.hasNext()) {
            Camera.Size supportedPreviewResolution = it.next();
            int width = supportedPreviewResolution.width;
            int height = supportedPreviewResolution.height;

            // 在camera分辨率与屏幕分辨率宽高比不相等的情况下，找出差距最小的一组分辨率
            // 由于camera的分辨率是width>height，我们设置的portrait模式中，width<height
            // 因此这里要先交换然后在比较宽高比
            boolean isCandidatePortrait = width > height;
            int maybeFlippedWidth = isCandidatePortrait ? height : width;
            int maybeFlippedHeight = isCandidatePortrait ? width : height;
            double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
            double distortion = Math.abs(aspectRatio - screenAspectRatio);
            if (distortion > MAX_ASPECT_DISTORTION) {
                it.remove();
                continue;
            }
            // 找到与屏幕分辨率完全匹配的预览界面分辨率直接返回
            if (maybeFlippedWidth == getScreenWidth()
                    && maybeFlippedHeight == getScreenHeight()) {
                return supportedPreviewResolution;
            }
        }

        // 如果没有找到合适的，并且还有候选的像素，对于照片，则取其中最大比例的，而不是选择与屏幕分辨率相同的
        if (!sortedSupportedPicResolutions.isEmpty()) {
            return sortedSupportedPicResolutions.get(0);
        }

        // 没有找到合适的，就返回默认的
        return defaultPictureResolution;
    }

    private void setUpPreviewSize(Camera.Parameters parameters) {

        if (previewSize != null) {
            return;
        } else {
            previewSize = findBestPreviewResolution();
        }
    }

    /**
     * 找出最适合的预览界面分辨率
     *
     * @return
     */
    private Camera.Size findBestPreviewResolution() {
        Camera.Parameters cameraParameters = mCamera.getParameters();
        Camera.Size defaultPreviewResolution = cameraParameters.getPreviewSize();

        List<Camera.Size> rawSupportedSizes = cameraParameters.getSupportedPreviewSizes();
        if (rawSupportedSizes == null) {
            return defaultPreviewResolution;
        }

        // 按照分辨率从大到小排序
        List<Camera.Size> supportedPreviewResolutions = new ArrayList<Camera.Size>(rawSupportedSizes);
        Collections.sort(supportedPreviewResolutions, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size a, Camera.Size b) {
                int aPixels = a.height * a.width;
                int bPixels = b.height * b.width;
                if (bPixels < aPixels) {
                    return -1;
                }
                if (bPixels > aPixels) {
                    return 1;
                }
                return 0;
            }
        });

        StringBuilder previewResolutionSb = new StringBuilder();
        for (Camera.Size supportedPreviewResolution : supportedPreviewResolutions) {
            previewResolutionSb.append(supportedPreviewResolution.width).append('x').append(supportedPreviewResolution.height)
                    .append(' ');
        }
        Log.v(TAG, "Supported preview resolutions: " + previewResolutionSb);


        // 移除不符合条件的分辨率
        double screenAspectRatio = (double) getScreenWidth()
                / (double) getScreenHeight();
        Iterator<Camera.Size> it = supportedPreviewResolutions.iterator();
        while (it.hasNext()) {
            Camera.Size supportedPreviewResolution = it.next();
            int width = supportedPreviewResolution.width;
            int height = supportedPreviewResolution.height;

            // 移除低于下限的分辨率，尽可能取高分辨率
            if (width * height < MIN_PREVIEW_PIXELS) {
                it.remove();
                continue;
            }

            // 在camera分辨率与屏幕分辨率宽高比不相等的情况下，找出差距最小的一组分辨率
            // 由于camera的分辨率是width>height，我们设置的portrait模式中，width<height
            // 因此这里要先交换然preview宽高比后在比较
            boolean isCandidatePortrait = width > height;
            int maybeFlippedWidth = isCandidatePortrait ? height : width;
            int maybeFlippedHeight = isCandidatePortrait ? width : height;
            double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
            double distortion = Math.abs(aspectRatio - screenAspectRatio);
            if (distortion > MAX_ASPECT_DISTORTION) {
                it.remove();
                continue;
            }

            // 找到与屏幕分辨率完全匹配的预览界面分辨率直接返回
            if (maybeFlippedWidth == getScreenWidth()
                    && maybeFlippedHeight == getScreenHeight()) {
                return supportedPreviewResolution;
            }
        }

        // 如果没有找到合适的，并且还有候选的像素，则设置其中最大比例的，对于配置比较低的机器不太合适
        if (!supportedPreviewResolutions.isEmpty()) {
            Camera.Size largestPreview = supportedPreviewResolutions.get(0);
            return largestPreview;
        }

        // 没有找到合适的，就返回默认的

        return defaultPreviewResolution;
    }

    public int getScreenWidth() {
        if (this.displayMetrics == null) {
            setDisplayMetrics(getResources().getDisplayMetrics());
        }
        return this.displayMetrics.widthPixels;
    }

    public void setDisplayMetrics(DisplayMetrics DisplayMetrics) {
        this.displayMetrics = DisplayMetrics;
    }

    public int getScreenHeight() {
        if (this.displayMetrics == null) {
            setDisplayMetrics(getResources().getDisplayMetrics());
        }
        return this.displayMetrics.heightPixels;
    }

    //控制图像的正确显示方向
    private void setDispaly(Camera.Parameters parameters, Camera camera) {
        if (Build.VERSION.SDK_INT >= 8) {
            setDisplayOrientation(camera, 90);
        } else {
            parameters.setRotation(90);
        }
    }

    //实现的图像的正确显示
    private void setDisplayOrientation(Camera camera, int i) {
        Method downPolymorphic;
        try {
            downPolymorphic = camera.getClass().getMethod("setDisplayOrientation",
                    new Class[]{int.class});
            if (downPolymorphic != null) {
                downPolymorphic.invoke(camera, new Object[]{i});
            }
        } catch (Exception e) {
            Log.e("Came_e", "图像出错");
        }
    }

    //实现自动对焦
    private void autoFocus() {
        new Thread() {
            @Override
            public void run() {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (mCamera == null) {
                    return;
                }
                mCamera.autoFocus(new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean success, Camera camera) {
                        if (success) {
                            initCamera();//实现相机的参数初始化
                        }
                    }
                });
            }
        };
    }


    /**
     * 上传人脸图片信息
     */
    private void UploadPicture(final String filePath_img) {

        HttpParams params = new HttpParams();
        params.put("token", mStrUserToken);
        //扫描用户id
        params.put("userId", mStrUserId);
        //拍摄的人脸图像
        params.put("headImgFile", new File(filePath_img));

        MyHttpsUtils.post(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.FACEIMAGE, params, new MyHttpsUtils.ResultCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    String msg = object.getString("msg");
                    String code = object.getString("code");
                    String compareImg=object.getString("compareImg");


                    if ("200".equals(code)) {
                        Toast.makeText(CameraActivity.this, msg, Toast.LENGTH_SHORT).show();
                        //保存认证通过状态
//                        SharedPreferences preferences = getSharedPreferences("user_state", Context.MODE_PRIVATE);
//                        SharedPreferences.Editor editor = preferences.edit();
//                        editor.putBoolean("user_head_state", true);
//                        editor.commit();
                        Realm realm = Realm.getDefaultInstance();
                        IdCard mIdCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
                        realm.beginTransaction();//开启事务
                        mIdCard.setCert(1);//
                        mIdCard.setCompareImg(compareImg);//返回的头像存储到数据库里面
                        realm.copyToRealmOrUpdate(mIdCard);//更新数据库对象
                        realm.commitTransaction();//提交事务
                        realm.close();

                        //SVProgressHUD.showSuccessWithStatus(CameraActivity.this, "认证成功！");

                        Intent intent = new Intent(CameraActivity.this, SettingCardActivity.class);
                        startActivity(intent);
                        finish();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.d("AAA", response);
            }

            @Override
            public void onFailure(String failReason) {
                Log.d("AAA", failReason);//这里认证失败
                SVProgressHUD.dismiss(CameraActivity.this);
                //SVProgressHUDAnimateUtil  时间长短类
                SVProgressHUD.showErrorWithStatus(CameraActivity.this, "认证失败，请重试", SVProgressHUD.SVProgressHUDMaskType.GradientCancel);
                mCamera.startPreview();// 拍完照后，重新开始预览

            }
        });
    }
}
